package com.ytc.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ytc.commons.model.dto.LoginDto;
import com.ytc.commons.model.vo.LoginVo;
import com.ytc.commons.model.vo.ResponseResult;
import com.ytc.commons.utils.JwtUtils;
import com.ytc.system.domain.User;
import com.ytc.system.mappers.UserMapper;
import com.ytc.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //1.验证参数判断是否为空
        String phone = dto.getUsername();
        String password = dto.getPassword();
        String utype = dto.getUtype();
        //2.根据用户去查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getPhone,phone);
        queryWrapper.eq(User::getUtype,utype);
        User user = userMapper.selectOne(queryWrapper);
        //2.1用户不存在
        if(user == null){
            throw new RuntimeException("用户不存在");
        }
        //2.2存在，比较密码
        String dbpassword = user.getPassword();
        password = DigestUtil.md5Hex(password);
        //3.判断输入密码是否正确  （加密）
        if(!dbpassword.equals(password)){
            //3.1密码不一致
            throw new RuntimeException("密码错误");
        }
        //3.2密码一致

        //4.生成JWT  token
        Map<String , Object> claimMaps = new HashMap<>();
        claimMaps.put("userId",user.getId());
        claimMaps.put("companyId",user.getCompanyId());
        claimMaps.put("companyName",user.getCompanyName());

        String token = JwtUtils.createToken(claimMaps,240); //存入数据，以及过期时间 ：分钟
        //5.构造返回数据
        LoginVo vo = new LoginVo();
        vo.setAccess_token(token);
        vo.setUsername(user.getName());

        ResponseResult result = new ResponseResult();
        result.setCode(0);
        result.setErrorMessage("成功");
        result.setData(vo);

       // return result; //下面那个方法也能返回数据

        return ResponseResult.okResult(vo);
    }

}
